package models;

import java.io.*;

import javax.swing.filechooser.FileSystemView;

public class TopTen {
	
	private static String rutaArchivo = ""+FileSystemView.getFileSystemView().getHomeDirectory() +"/toptenfile.txt";
	private String[] scores;

    public TopTen()
    {
        scores = new String[10];
        readScores();
    }
    
    public boolean isTop(int puntaje) {
    	boolean flag=false;
    	for(int i=0; i<10;i++)
    		if(puntaje>ChopNumber(scores[i]))
    			flag=true;
    	return flag;
    }
        
    
	
    public void refreshScores(int newScore, String name) {  //insertar en un arreglo ordenado..
       //introduces new score if applicable to top ten
    	readScores();
    	int i=0;
    	boolean notTopScore=true;
    	while(i<10&&notTopScore){
    		if (newScore>ChopNumber(scores[i]))
    				notTopScore=false;
    		else
    			i++;
    	}
    	if(!notTopScore) //it is actually a top score
    	{
    		String newTopScore= name +" "+ newScore;
    		for(int j=9; j>i; j--)
    			scores[j]=scores[j-1];
    		scores[i]=newTopScore;
    	}
    	
    	writeScores();  //refreshes archive.
    }
    
    private int ChopNumber(String score) {  //gets number from stringscore
    	int i=0;
    	while(i<score.length()&&!Character.isDigit(score.charAt(i)))
    		i++;
    	String numberscore=score.substring(i, score.length()).trim();
    	return Integer.parseInt(numberscore);
    	

    		
    	
    }
    
    public String[] getTopTenScores() { //la vista escribe los strings que recibe.
    	return scores;
    }
	
	private void writeScores() {
		try {
			//Escritura
			java.io.BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(rutaArchivo));
			
			for(int i=0; i<scores.length; i++)
			{
				bufferedWriter.append(scores[i]);
				bufferedWriter.flush();
				bufferedWriter.newLine();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	}
	}
	
	private void readScores(){
		try {
			//Entrada
			BufferedReader bufferedReader = new BufferedReader(new FileReader(rutaArchivo));
			
			//Buscar si existe una palabra
			String line = "";
			int i=0;
			while((line = bufferedReader.readLine())!=null){
	                         scores[i]=line;
	                         i++;
				}
			
			while(i<10)
			{
			 scores[i]= "- 0"; //en caso de que no haya 10 puntajes maximos todavia: relleno..
			 i++;
			}
		} 
		catch (FileNotFoundException e) 
		{
			File file = new File(rutaArchivo);
			try 
			{
				file.createNewFile();
				for(int i = 0; i < 10; ++i)
					scores[i]= "no data - 0";
			} 
			catch (IOException e1) 
			{

			}
		} 
		catch (IOException e) {e.printStackTrace();
		}
	}

}